package br.com.comanda.restclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class RestClient {

	private String toString(InputStream is) throws IOException {
		byte[] bytes = new byte[1024];
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		int read;

		while ((read = is.read(bytes)) > 0) {
			baos.write(bytes, 0, read);
		}

		return new String(baos.toByteArray());
	}

	public String getRESTFileContent(String url) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);

		try {
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream inputStream = entity.getContent();
				String result = toString(inputStream);

				inputStream.close();
				return result;
			}
		} catch (Exception e) {
			Log.e("CLIENT", "Falha ao acessar webservice");
		}

		return null;
	}

	public String put(String url) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPut httpPut = new HttpPut(url);

		try {
			HttpResponse response = httpClient.execute(httpPut);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream inputStream = entity.getContent();
				String result = toString(inputStream);

				inputStream.close();
				return result;
			}
		} catch (Exception e) {
			Log.e("CLIENT", "Falha ao acessar webservice");
		}

		return null;
	}

	public void readAllBoards() {
		String result = getRESTFileContent("http://192.168.0.182:8080/projeto-comanda-webservice/boards");

		try {
			JSONObject json = new JSONObject(result);
			JSONArray boards = json.getJSONArray("boardVO");

			JSONObject boardJson;

			for (int i = 0; i < boards.length(); i++) {
				boardJson = new JSONObject(boards.getString(i));

				Log.i("RESTCLIENT", "-----------------------------------");
				Log.i("RESTCLIENT", "ID: " + boardJson.getInt("id"));
				Log.i("RESTCLIENT", "BOARD: " + boardJson.getString("board"));

			}

		} catch (JSONException e) {
			Log.e("RESTCLIENT", "ERRO no parsing do JSON");
		}

	}
}
